//index.js
//获取应用实例
const app = getApp();
import {
  SERVERS_INFO,
  SERVERS_ALIAS
} from '../../utils/api.js'

import {
  http
} from '../../utils/network.js'
import {
  PATHS_ALIAS
} from '../../utils/api.js'

Page({
  data: {
    hasUserInfo: true, //是否已经授权
    impowerShow: wx.getStorageSync('impowerShow') == 'hide' ? 'hide' : 'show', //授权提示弹框是否被关闭过
    canIUse: wx.canIUse('button.open-type.getUserInfo'), //判断小程序的API，回调，参数，组件等是否在当前版本可用。
    wxUserInfo: null, //微信用户信息
    session_key: null, //会话密钥
  },
  onLoad: function () {
    this.login();
  },
  // 登录授权
  login: function () {
    let _this = this;
    // 判断微信版本
    this.checkVersion();
    // 登录
    wx.login({
      success: res => {
        // console.log(res);
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        this.getUserMsg(res.code);
      }
    });
    // 获取用户授权信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              console.log(res);
              // 可以将 res 发送给后台解码出 unionId
              app.globalData.userInfo = res.userInfo
              _this.setData({
                wxUserInfo: res,
                hasUserInfo: true
              });
              _this.getUnionId();
            }
          })
        } else if (_this.data.canIUse) {
          // 没有授权，弹框提示授权
          this.setData({
            hasUserInfo: false
          })
        } else {
          // 在没有 open-type=getUserInfo 版本的兼容处理
          wx.getUserInfo({
            success: res => {
              app.globalData.userInfo = res.userInfo
              this.setData({
                wxUserInfo: res.userInfo,
                hasUserInfo: true
              });
              _this.getUnionId();
            }
          })
        }
      }
    })
  },
  // code换取用户信息
  getUserMsg: function (code) {
    let _this = this;
    let params = {
      code: code,
      type: 'city'
    };
    http({
      path: PATHS_ALIAS.GET_OPEN_INFO,
      params: params,
      success: function (res) {
        console.log(res);
        app.globalData.openId = res.response.openid;
        app.globalData.session_key = res.response.session_key;
        _this.setData({
          session_key: res.response.session_key
        });
      },
      complete: function () {

      }
    })
  },
  // 获取unionID
  getUnionId: function () {
    let _this = this;
    // 请求参数齐全
    if (this.data.wxUserInfo && app.globalData.openId) {

    } else {
      setTimeout(function () {
        _this.getUnionId();
      }, 100);
      return;
    }


    // 用户获取union
    let params = {
      encryptedData: this.data.wxUserInfo.encryptedData,
      iv: this.data.wxUserInfo.iv,
      openId: app.globalData.openId,
      rawData: this.data.wxUserInfo.rawData,
      sessionKey: this.data.session_key,
      signature: this.data.wxUserInfo.signature,
      type: 'city'
    };
    http({
      path: PATHS_ALIAS.GET_UNION_ID,
      params: params,
      success: function (res) {
        console.log(res);
        if (res.code == '0') {
          app.globalData.unionId = res.response.unionId;
          wx.setStorageSync('openId', app.globalData.openId)
          wx.setStorageSync('unionId', res.response.unionId)
          // 判断第三方登录关系
          _this.loginThird();
        } else {

        }
      },
      fail: function (err) {
        wx.showToast({
          title: '登录失败',
          icon: 'none'
        })
      },
      complete: function () {

      }
    })
  },
  // 第三方用户登录
  loginThird: function () {
    let host = SERVERS_INFO[SERVERS_ALIAS.SMK_BASE].host;
    let params = {
      logType: '07',
      thirdId: app.globalData.unionId,
      resId: 'weixin',
      userSystem: '0052'
    };

    wx.request({
      url: host + '/ThirdUserLogin',
      header: app.globalData.ajaxHeader,
      method: 'POST',
      data: params,
      success: function (res) {
        console.log(res)

      },
      fail: function (res) {

      }
    })
  },
  // 获取用户信息-处理数据
  bindgetuserinfo: function (e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo;
    this.setData({
      wxUserInfo: e.detail,
      hasUserInfo: true
    });
    this.getUnionId();
  },
  // 授权弹框-取消
  cancelGetInfo: function () {
    let _this = this;
    wx.setStorage({
      key: 'impowerShow',
      data: 'hide',
      success: function () {
        _this.setData({
          impowerShow: 'hide'
        })
      }
    })
  },
  // 显示模态对话框 ———— 版本过低提示
  checkVersion: function () {
    let _this = this;
    wx.getSystemInfo({
      success: function (res) {
        // console.log(res);
        let version = res.SDKVersion;
        version = version.replace(/\./g, '');
        if (parseInt(version) < 167) { //小于 1.6.7的版本
          wx.showModal({
            title: '提示',
            content: '微信版本过低，请前往升级微信',
            showCancel: false,
            success: function (res) {
              // console.log(res)
              if (res.confirm) {
                _this.openModal()
              }
            }
          })
          return;
        }
      }
    });
  },
  // 二次授权
  loginAgain: function () {
    this.selectComponent('#loginCheck').loginAgain();
  }
})